package dat255.calendarclock.model.event;

import java.util.Comparator;
import java.util.GregorianCalendar;

public class DateHelper implements Comparator<GregorianCalendar> {
	
	private static final int[] timeHierarchy = { GregorianCalendar.SECOND, // 13
		GregorianCalendar.MINUTE, // 12
		GregorianCalendar.HOUR_OF_DAY, // 11
		GregorianCalendar.DATE, // 5
		GregorianCalendar.MONTH, // 2
		GregorianCalendar.YEAR // 1
	};
	
	/**
	 * This is completely retarded in the API. There's no reset for the fields
	 * in the date...
	 */
	private static final int[] timeHierarchyResetValue = { 0, // Second
			0, // Minute
			0, // Hour
			1, // Date
			0, // Month
			0, // Year
	};
	
	@Override
	public int compare(final GregorianCalendar arg1, final GregorianCalendar arg2) {
		if (arg2 == null && arg1 != null){
			return 1;
		}
		GregorianCalendar date1 = reset((GregorianCalendar) arg1.clone(), GregorianCalendar.DATE);
		GregorianCalendar date2 = reset((GregorianCalendar) arg2.clone(), GregorianCalendar.DATE);
		if(date1.after(date2))
			return 1;
		if(date1.before(date2))
			return -1;
		return 0;
	}
	
	
	
	/**
	 * Resets the date to the specified precision.
	 * 
	 * @param date
	 * @param precision
	 *            use GregorianCalendar constants
	 */
	public static GregorianCalendar reset(GregorianCalendar date, int precision) {
		for (int i = 0; i < timeHierarchy.length; i++) {
			if (precision == timeHierarchy[i]) {
				for (int j = (i - 1); j >= 0; j--) {
					date.set(timeHierarchy[j], timeHierarchyResetValue[j]);
				}
				return date;
			}
		}
		throw new IllegalArgumentException(
				"Could not read precision as a GregorianCalendar constant.");
	}
	
	/**
	 * Since GregorianCalendar dont have a working one.
	 * @param g1 first one to compare
	 * @param g2 second one to compare
	 * @return
	 */
	public static boolean gregoriansAreEqual(GregorianCalendar g1 ,GregorianCalendar g2) {
		return g1.get(GregorianCalendar.YEAR) == g2.get(GregorianCalendar.YEAR) &&
				g1.get(GregorianCalendar.MONTH) == g2.get(GregorianCalendar.MONTH) &&
				g1.get(GregorianCalendar.DATE) == g2.get(GregorianCalendar.DATE) &&
				g1.get(GregorianCalendar.HOUR) == g2.get(GregorianCalendar.HOUR) &&
				g1.get(GregorianCalendar.MINUTE) == g2.get(GregorianCalendar.MINUTE);
	}
}
